﻿namespace DocumentSearch32Lib
{
    using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Web;
    using System.IO;
    using System.Data;
    using System.Collections.ObjectModel;
    using dtSearch32Lib;
    using DocumentSearchServiceModel;

    public class SearchBll
    {
        static dtengine.SearchJob sj = new dtengine.SearchJob();
        static dtengine.SearchResults results = null;// new dtengine.SearchResults();

        public static SearchResultCls Execute(string SiteId, SearchParamCls OSearchParam)
        {
            System.IO.FileInfo[] Resultfi = null;
            SearchResultCls OSearchResultAttr = ExecuteAttribute(SiteId, OSearchParam);
            if (OSearchParam.ActiveFullTextSearch)
            {
                Resultfi = ExecuteAttachDoc(SiteId, OSearchParam);
                if (Resultfi.Length == 0)
                {
                    OSearchResultAttr.SearchResultItems.Clear();
                    OSearchResultAttr.TotalFound = 0;
                    OSearchResultAttr.PageIndex = 0;
                }
                else
                {
                    //doan nay xoa di
                    for (int iIndex = 0; iIndex < OSearchResultAttr.SearchResultItems.Count; iIndex++)
                    {
                        OSearchResultAttr.SearchResultItems[iIndex].Marked = false;
                    }
                    for (int iIndex = 0; iIndex < Resultfi.Length; iIndex++)
                    {
                        DataSet ds = new DataSet();
                        string XmlFile = Resultfi[iIndex].FullName + ".xml";
                        if (System.IO.File.Exists(XmlFile))
                        {
                            ds.ReadXml(Resultfi[iIndex].FullName + ".xml");
                            string ItemDataId = (string)ds.Tables[0].Rows[0]["DataId"];
                            ds.Clear();
                            ds.Dispose();
                            for (int zIndex = 0; zIndex < OSearchResultAttr.SearchResultItems.Count; zIndex++)
                            {
                                if (OSearchResultAttr.SearchResultItems[zIndex].DocumentId.Equals(ItemDataId))
                                {
                                    OSearchResultAttr.SearchResultItems[zIndex].Marked = true;
                                    break;
                                }
                            }
                        }
                    }
                }
                if (OSearchResultAttr.SearchResultItems.Count > 0)
                {
                    int iIndex = 0;
                    while (true)
                    {
                        if (OSearchResultAttr.SearchResultItems[iIndex].Marked == false)
                        {
                            OSearchResultAttr.SearchResultItems.RemoveAt(iIndex);
                            if (iIndex == OSearchResultAttr.SearchResultItems.Count) break;
                        }
                        else
                        {
                            iIndex++;
                            if (iIndex == OSearchResultAttr.SearchResultItems.Count) break;
                        }
                    }
                    OSearchResultAttr.TotalFound = OSearchResultAttr.SearchResultItems.Count;
                }
            }


            return OSearchResultAttr;
        }

        public static SearchResultCls ExecuteAttribute(string SiteId, SearchParamCls OSearchParam)
        {
            SearchResultCls OSearchResult = new SearchResultCls();
            try
            {
                string SearchRequest = SearchParser.GetSearchCondition(OSearchParam);
                string IndexesToSearch = OSearchParam.IndexesToSearch;
                sj.Request = SearchRequest;
                sj.PhonicSearching = false;
                sj.Stemming = false;
                sj.NaturalLanguage = false;
                sj.Synonyms = false;
                sj.UserSynonyms = false;
                sj.WordNetSynonyms = false;
                sj.WordNetRelated = false;
                sj.IndexesToSearch = IndexesToSearch;
                sj.DirToSearch = "";// DirToSearch.Text;
                sj.IncludeFilters = "*.xml";
                sj.ExcludeFilters = "";

                //sj.OutputListingName = "search.lst";
                sj.OutputListingHits = true; ;

                sj.MaxFilesToRetrieve = OSearchParam.MaxFilesToRetrieve;
                sj.TimeoutSeconds = OSearchParam.TimeoutSeconds;
                //sj.SearchFlags = (dtengine.SearchFlag)dtengine.SearchFlag.dtsSearchWantHitDetails;//(sj.SearchFlags || dtengine.SearchFlag.dtsSearchWantHitDetails);

                sj.ExecuteInThread();
                while (sj.IsThreadDone == false)
                {

                }
                results = (dtengine.SearchResults)sj.Results;

                int CurrentPage = OSearchParam.PageIndex;
                int PageSize = OSearchParam.PageSize;

                SearchReturnPaging OReturnPaging = PagingUtilities.GetPaging(results.Count, CurrentPage, PageSize, 10, OSearchParam.JumpPageJavascript, 0);
                int PageCount = OReturnPaging.TotalPage;


                //if (results.Count % PageSize != 0)
                //{
                //    PageCount++;
                //}
                int StartIndex = OReturnPaging.StartIndex;
                int EndIndex = OReturnPaging.EndIndex;
                if (PageCount <= 1)
                {
                    PageCount = 1;
                    StartIndex = 0;
                    EndIndex = results.Count;
                    OSearchResult.PageIndex = 1;
                    OSearchResult.MaxPage = 1;
                }
                else
                {
                    StartIndex = PageSize * CurrentPage;
                    EndIndex = StartIndex + PageSize;
                    if (EndIndex > results.Count) EndIndex = results.Count;
                    OSearchResult.PageIndex = CurrentPage + 1;
                    OSearchResult.MaxPage = PageCount;
                }

                dtengine.JobErrorInfo ei = new dtengine.JobErrorInfo();
                ei = (dtengine.JobErrorInfo)sj.Errors;

                int MaxResult = EndIndex - StartIndex;
                Collection<SearchResultItemCls> SearchResultItems = new Collection<SearchResultItemCls> { };
                results.SetSortKey(OSearchParam.SortField);
                if (OSearchParam.SortType.Equals("DESC"))
                {
                    results.Sort(0x40 & 0x2, OSearchParam.SortField);
                }
                else
                {
                    results.Sort(0x40, OSearchParam.SortField);
                }

                int Count = 0;
                for (int iIndex = StartIndex; iIndex < EndIndex; iIndex++)
                {
                    results.GetNthDoc(iIndex);

                    //doan nay doi ten da
                    string FileName = results.DocName;
                    int iFound = FileName.IndexOf("DocumentArchives");
                    if (iFound != -1)
                    {
                        FileName = FileName.Substring(iFound);
                        FileName = OSearchParam.DataRoot + "\\" + FileName;
                    }
                    System.IO.FileInfo fi = new System.IO.FileInfo(FileName);

                    SearchResultItemCls OSearchResultItem = new SearchResultItemCls();
                    if (System.IO.File.Exists(fi.FullName))
                    {
                        DataSet ds = new DataSet();
                        ds.ReadXml(fi.FullName);

                        OSearchResultItem.DocumentId = (string)ds.Tables[0].Rows[0]["DataId"];
                        OSearchResultItem.Subject = (string)ds.Tables[0].Rows[0]["Subject"];
                        OSearchResultItem.DocumentNo = (string)ds.Tables[0].Rows[0]["DataAlias"];
                        OSearchResultItem.Description = (string)ds.Tables[0].Rows[0]["Description"];

                        OSearchResultItem.DocReleaseFrom = (string)ds.Tables[0].Rows[0]["DocReleaseFromName"];
                        OSearchResultItem.DocReleaseFromId = (string)ds.Tables[0].Rows[0]["frkDocReleaseFromId"];
                        OSearchResultItem.DocReleaseFromId = OSearchResultItem.DocReleaseFromId.Replace("$", "");

                        OSearchResultItem.DocField = (string)ds.Tables[0].Rows[0]["DocFieldName"];
                        OSearchResultItem.DocFieldId = (string)ds.Tables[0].Rows[0]["frkDocFieldId"];
                        OSearchResultItem.DocFieldId = OSearchResultItem.DocFieldId.Replace("$", "");

                        OSearchResultItem.DocSigner = (string)ds.Tables[0].Rows[0]["DocSignerName"];
                        OSearchResultItem.DocSignerId = (string)ds.Tables[0].Rows[0]["frkDocSignerId"];
                        OSearchResultItem.DocSignerId = OSearchResultItem.DocSignerId.Replace("$", "");

                        OSearchResultItem.DocType = (string)ds.Tables[0].Rows[0]["DocTypeName"];
                        OSearchResultItem.DocTypeId = (string)ds.Tables[0].Rows[0]["frkDocTypeId"];
                        OSearchResultItem.DocTypeId = OSearchResultItem.DocTypeId.Replace("$", "");


                        OSearchResultItem.ReleaseDate = (string)ds.Tables[0].Rows[0]["ReleaseDate"];
                        OSearchResultItem.EffectedDate = (string)ds.Tables[0].Rows[0]["EffectedDate"];
                        OSearchResultItem.SignDate = (string)ds.Tables[0].Rows[0]["SignDate"];
                        OSearchResultItem.IsPublic = int.Parse(ds.Tables[0].Rows[0]["IsPublic"].ToString());
                        OSearchResultItem.DocStatus = ds.Tables[0].Rows[0]["DocStatus"].ToString();
                        try
                        {
                            OSearchResultItem.IsNew = int.Parse(ds.Tables[0].Rows[0]["IsNew"].ToString());
                        }
                        catch { }
                        try
                        {
                            OSearchResultItem.AttachedSearchable = int.Parse(ds.Tables[0].Rows[0]["AttachedSearchable"].ToString());
                        }
                        catch { }
                        try
                        {
                            OSearchResultItem.NeedApproved = int.Parse(ds.Tables[0].Rows[0]["NeedApproved"].ToString());
                        }
                        catch { }
                        SearchResultItems.Add(OSearchResultItem);
                        Count++;
                        ds.Clear();
                    }
                    else
                    {
                        //throw new Exception(fi.FullName + " not found");
                    }
                }

                if (results.Count == 0)
                {
                    OSearchResult.MaxPage = 0;
                    OSearchResult.TotalFound = 0;
                }
                OSearchResult.PaggingText = OReturnPaging.PagingText;
                OSearchResult.SearchResultItems = SearchResultItems;
                OSearchResult.SearchOk = true;
                OSearchResult.TotalFound = Count;
                OSearchResult.InfoMessage = "";
                OSearchResult.StartIndex = OReturnPaging.StartIndex;
                OSearchResult.QuerySearch = SearchRequest;
            }
            catch (Exception ex)
            {
                OSearchResult.SearchOk = false;
                OSearchResult.InfoMessage = ex.Message.ToString();
            }

            return OSearchResult;
        }



        public static FileInfo[] ExecuteAttachDoc(string SiteId, SearchParamCls OSearchParam)
        {
            SearchResultCls OSearchResult = new SearchResultCls();
            try
            {
                string SearchRequest = SearchParser.GetSearchCondition(OSearchParam);
                string IndexesToSearchAttachDoc = OSearchParam.IndexesToSearchAttachDoc;
                sj.Request = OSearchParam.fullTextSearchKeyword;
                sj.PhonicSearching = false;
                sj.Stemming = false;
                sj.NaturalLanguage = false;
                sj.Synonyms = false;
                sj.UserSynonyms = false;
                sj.WordNetSynonyms = false;
                sj.WordNetRelated = false;
                sj.IndexesToSearch = IndexesToSearchAttachDoc;
                sj.DirToSearch = "";// DirToSearch.Text;
                sj.IncludeFilters = "*.xml";
                sj.ExcludeFilters = "";

                //sj.OutputListingName = "search.lst";
                sj.OutputListingHits = true; ;

                sj.MaxFilesToRetrieve = OSearchParam.MaxFilesToRetrieve;
                sj.TimeoutSeconds = OSearchParam.TimeoutSeconds;
                //sj.SearchFlags = (dtengine.SearchFlag)dtengine.SearchFlag.dtsSearchWantHitDetails;//(sj.SearchFlags || dtengine.SearchFlag.dtsSearchWantHitDetails);


                sj.ExecuteInThread();
                while (sj.IsThreadDone == false)
                {

                }
                results = (dtengine.SearchResults)sj.Results;



                dtengine.JobErrorInfo ei = new dtengine.JobErrorInfo();
                ei = (dtengine.JobErrorInfo)sj.Errors;

                int MaxResult = results.Count;
                FileInfo[] Results = new FileInfo[MaxResult];
                int Count = 0;
                for (int iIndex = 0; iIndex < MaxResult; iIndex++)
                {
                    results.GetNthDoc(iIndex);
                    string FileName = results.DocName;
                    int iFound = FileName.IndexOf("DocumentArchives");
                    if (iFound != -1)
                    {
                        FileName = FileName.Substring(iFound);
                        FileName = OSearchParam.DataRoot + "\\" + FileName;
                    }
                    //doan nay doi ten da
                    System.IO.FileInfo fi = new System.IO.FileInfo(FileName);
                    Results[Count] = fi;

                    Count++;
                }

                return Results;
            }
            catch (Exception ex)
            {
                ex.Source = "";
                return null;
            }
        }
    }
}